package database

import (
	"fmt"

	"github.com/starter-go/rbac"
	"gorm.io/gorm"
)

// Finder 是条件化查询数据库的便捷工具
type Finder struct {
	DB          *gorm.DB
	Pagination  *rbac.Pagination
	ItemModel   any
	ListModel   any
	QueryString string
	QueryArgs   []any
}

// Find ...
func (inst *Finder) Find() error {

	db := inst.DB
	list := inst.ListModel
	item := inst.ItemModel
	qStr := inst.QueryString
	qArgs := inst.QueryArgs
	page := inst.Pagination

	if db == nil {
		return fmt.Errorf("DB is nil")
	}

	if item != nil {
		db = db.Model(item)
	}

	// where
	if qStr != "" {
		db = db.Where(qStr, qArgs...)
	}

	// limit & offset & count
	if page != nil {
		var count = int64(0)
		tx := db.Count(&count)
		if tx.Error == nil {
			page.Total = count
		}
		db = db.Offset(int(page.Offset())).Limit(int(page.Limit()))
	}

	// find
	res := db.Find(list)
	return res.Error
}
